package cn.stylefeng.guns.modular.demo.controller;

import cn.stylefeng.guns.core.exception.BusinessException;
import cn.stylefeng.guns.core.exception.BusinessExceptionEnum;
import cn.stylefeng.guns.dao.IGaiaProductBusinessService;
import cn.stylefeng.guns.dao.IGoodsService;
import cn.stylefeng.guns.dao.ISaleStockService;
import cn.stylefeng.guns.dao.entity.*;
import cn.stylefeng.guns.dao.impl.SupplierServiceImpl;
import cn.stylefeng.guns.dao.mapper.UserExtendMapper;
import cn.stylefeng.guns.dao.service.IGaiaBatchInfoService;
import cn.stylefeng.guns.dao.service.ISaleStockImportTimeService;
import cn.stylefeng.guns.dao.service.IUserExtendService;
import cn.stylefeng.guns.dao.service.impl.UserExtendServiceImpl;
import cn.stylefeng.guns.modular.demo.controller.domain.GoodsQueryRequest;
import cn.stylefeng.guns.modular.demo.controller.domain.ImportQueryRequest;
import cn.stylefeng.guns.modular.demo.excel.domain.asilikang.AsSaleExcelVO;
import cn.stylefeng.guns.modular.demo.excel.domain.asilikang.shenji.PeisongExcelVo;
import cn.stylefeng.guns.modular.demo.excel.listener.aslikang.StockAsSaleListener;
import cn.stylefeng.guns.modular.demo.excel.listener.aslikang.shenji.SalePeisongListener;
import cn.stylefeng.guns.modular.demo.service.SyncService;
import cn.stylefeng.guns.modular.demo.service.TestBizService;
import cn.stylefeng.guns.util.ConfigUtil;
import cn.stylefeng.guns.util.RebateDateUtil;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.annotation.BusinessLog;
import cn.stylefeng.roses.kernel.rule.enums.ResBizTypeEnum;
import cn.stylefeng.roses.kernel.rule.pojo.response.ResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.SuccessResponseData;
import cn.stylefeng.roses.kernel.scanner.api.annotation.ApiResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.GetResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.PostResource;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import static cn.stylefeng.guns.modular.demo.service.SyncService.SIMPLE_DATE_FORMAT1;

/**
 * 导入
 *
 * @author fengshuonan
 * @since 2021/1/24 10:57
 */
@RestController
@ApiResource(name = "导入", path = "/import", resBizType = ResBizTypeEnum.BUSINESS)
@Slf4j
public class ImportController {

    @Resource
    private TestBizService testBizService;
    @Resource
    private ISaleStockService saleStockService;


    @Resource
    IGoodsService goodsService;
    @Resource
    private IGaiaProductBusinessService gaiaProductBusinessService;
    @Resource
    IGaiaBatchInfoService gaiaBatchInfoService;
    @Resource
    private ISaleStockImportTimeService saleStockImportTimeService;


    @Resource
    private SyncService syncService;
    @Autowired
    private UserExtendMapper userExtendMapper;
    @Autowired
    private IUserExtendService userExtendService;
    @Autowired
    private SupplierServiceImpl supplierServiceImpl;


    @GetResource(name = "/add", path = "/add", requiredLogin = false, requiredPermission = false)
    @ApiOperation("新增导入时间段")
    public ResponseData<String> add(@RequestParam("userId") Long userid,
                                    @RequestParam("type") String type,
                                    @RequestParam("startTime")
                                    @DateTimeFormat(pattern = "yyyy-MM-dd")
                                    LocalDate startTime,
                                    @RequestParam("endTime")
                                    @DateTimeFormat(pattern = "yyyy-MM-dd")
                                    LocalDate endTime) throws IOException {
        Long count = saleStockImportTimeService.count(Wrappers.<SaleStockImportTime>lambdaQuery()
                .eq(SaleStockImportTime::getUserId, userid)
                .eq(SaleStockImportTime::getType, type)
                .ge(SaleStockImportTime::getStartTime, startTime)
                .le(SaleStockImportTime::getEndTime, endTime)
        );
        if (count > 0) {
            throw new BusinessException(BusinessExceptionEnum.TIME_NOT_EXIST);
        }
        SaleStockImportTime saleStockImportTime = new SaleStockImportTime();
        saleStockImportTime.setUserId(userid);
        saleStockImportTime.setStartTime(startTime);
        saleStockImportTime.setEndTime(endTime);
        saleStockImportTime.setType(type);
        saleStockImportTime.setSaleStockImportTimeId(UUID.randomUUID().toString());
        saleStockImportTimeService.save(saleStockImportTime);
        return new SuccessResponseData<>();
    }

    @GetResource(name = "/delete", path = "/delete", requiredLogin = false, requiredPermission = false)
    @ApiOperation("新增导入时间段")
    public ResponseData<String> delete(@RequestParam(value = "saleStockImportTimeId") Long saleStockImportTimeId) throws IOException {
        SaleStockImportTime saleStockImportTime = saleStockImportTimeService.getById(saleStockImportTimeId);
        if (Objects.isNull(saleStockImportTime)) {
            throw new BusinessException(BusinessExceptionEnum.TIME_NOT_EXIST);
        }
        LocalDate startTime = saleStockImportTime.getStartTime();
        LocalDate endTime = saleStockImportTime.getEndTime();
        Long userid = saleStockImportTime.getUserId();
        String type = saleStockImportTime.getType();

        UserExtend one = userExtendService.getOne(Wrappers.<UserExtend>lambdaQuery().eq(UserExtend::getUserId, userid));
        //先删除老数据
        saleStockService.remove(Wrappers.<SaleStock>lambdaQuery()
                .ge(SaleStock::getSaleTime, RebateDateUtil.getStartOfDayTimestamp(saleStockImportTime.getStartTime()))
                .le(SaleStock::getSaleTime, RebateDateUtil.getEndOfDayTimestamp(saleStockImportTime.getEndTime()))
                .eq(SaleStock::getTag, one.getClientId()).eq(SaleStock::getType, saleStockImportTime.getType()));
        return new SuccessResponseData<>();
    }

    @PostResource(name = "导入时间段列表", path = "/list", requiredLogin = true, requiredPermission = true)
    @ApiOperation("导入时间段列表")
    public ResponseData<PageResult<SaleStockImportTime>> list(@RequestBody ImportQueryRequest queryRuleRequest) {
        Page<SaleStockImportTime> page = new Page<>();
        page.setCurrent(queryRuleRequest.getPageNo());
        page.setSize(queryRuleRequest.getPageSize());
        LambdaQueryWrapper<SaleStockImportTime> lambdaQueryWrapper = Wrappers.<SaleStockImportTime>lambdaQuery()
                .eq(!StringUtils.isEmpty(queryRuleRequest.getUserId()), SaleStockImportTime::getUserId, queryRuleRequest.getUserId())
                .eq(!StringUtils.isEmpty(queryRuleRequest.getType()), SaleStockImportTime::getType, queryRuleRequest.getType());

        Page<SaleStockImportTime> page1 = saleStockImportTimeService.page(page, lambdaQueryWrapper);
        return new SuccessResponseData<>(PageResultFactory.createPageResult(page1));
    }


    @PostResource(name = "sync/peisong/import", path = "sync/peisong/import", requiredLogin = false, requiredPermission = false)
    @PostMapping(headers = "content-type=multipart/form-data")
    public ResponseData<String> syncTestAslikang(@RequestParam(value = "file") @RequestPart MultipartFile file,
                                                 @RequestParam(value = "saleStockImportTimeId") Long saleStockImportTimeId) throws IOException {
        SaleStockImportTime saleStockImportTime = saleStockImportTimeService.getById(saleStockImportTimeId);
        if (Objects.isNull(saleStockImportTime)) {
            throw new BusinessException(BusinessExceptionEnum.TIME_NOT_EXIST);
        }
        LocalDate startTime = saleStockImportTime.getStartTime();
        LocalDate endTime = saleStockImportTime.getEndTime();
        Long userid = saleStockImportTime.getUserId();
        String type = saleStockImportTime.getType();

        UserExtend one = userExtendService.getOne(Wrappers.<UserExtend>lambdaQuery().eq(UserExtend::getUserId, userid));

        //先删除老数据
        saleStockService.remove(Wrappers.<SaleStock>lambdaQuery()
                .ge(SaleStock::getSaleTime, RebateDateUtil.getStartOfDayTimestamp(saleStockImportTime.getStartTime()))
                .le(SaleStock::getSaleTime, RebateDateUtil.getEndOfDayTimestamp(saleStockImportTime.getEndTime()))
                .eq(SaleStock::getTag, one.getClientId()).eq(SaleStock::getType, saleStockImportTime.getType()));

        ArrayList<String> errorList = Lists.newArrayList();
        if (Objects.equals(type, "store")) {
            EasyExcel.read(file.getInputStream(), AsSaleExcelVO.class, new StockAsSaleListener(saleStockService, supplierServiceImpl, goodsService, errorList, gaiaBatchInfoService, one.getClientId())).sheet().doRead();
        } else if (Objects.equals(type, "supplier")) {

        } else if (Objects.equals(type, "sale")) {

        }


        return new SuccessResponseData<>(String.join(",", errorList));
    }


}
